package com.etrans.web.gps.business.areaTask.service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.areaTask.domain.AreaAnalyzesVo;
import com.etrans.web.gps.business.areaTask.domain.OrganzationVO;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.SendMessageRecord;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.message.MailInfo;
import com.etrans.web.gps.util.message.MailSendUtil;

@Service
public class AreaSendMessageService extends BaseService{
	
	@Autowired
	private Config config;
	
	
	/**
	 * 查询所有的区域
	 * @return 
	 */
	public List<OrganzationVO> queryAllAreaList(HashMap<String, Object> param) {
		List<OrganzationVO> list  = selectList("organzationMapper.queryAllOrganzationList",param);
		return list;
	}
	public List<HashMap<String, Object>> queryAreaTree(HashMap<String, Object> param) {
		List<HashMap<String, Object>> list  = selectList("organzationMapper.queryAreaTree",param);
		return list;
	}
	public String queryAreaFullID(Integer areaId) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("areaId", areaId);
		String fullID  = selectOne("organzationMapper.queryAreaFullID",param);
		return fullID;
	}
	
	/**
	 * 按周查询
	 * @param todayStr
	 * @return
	 * @throws ParseException 
	 */
	public List<AreaAnalyzesVo> queryAreaAnalyzesWeek(String queryTime) throws ParseException{
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		HashMap<String,Object> sortMap=new HashMap<String,Object>();
		Pattern pattern = Pattern.compile("^"+queryTime);
		whereMap.put("_id", pattern);
		sortMap.put("score", -1);
		List<AreaAnalyzesVo> listAnalyzes = MGTemplete.find("egov", "area_swap_week",whereMap,sortMap,AreaAnalyzesVo.class);
		sortList(listAnalyzes);
		return  listAnalyzes;
	}
	
	/**
	 * 按月查询
	 * @param todayStr
	 * @return
	 */
	public List<AreaAnalyzesVo> queryAreaAnalyzesMonth(String previousMonth){
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		Pattern pattern = Pattern.compile("^"+previousMonth);
		whereMap.put("_id", pattern);
		List<AreaAnalyzesVo> listAnalyzes = MGTemplete.find("egov", "area_swap_curMonth",whereMap,AreaAnalyzesVo.class,true);
		Collections.sort(listAnalyzes,Collections.reverseOrder(new Comparetores()));
		sortList(listAnalyzes);
		return  listAnalyzes;
	}
	
	public void saveMessage(SendMessageRecord smr) {
		MGTemplete.insertOne("egov", "tips_record", smr);
	}
	
	/**
	 * 对集合进行排序
	 */
	public static class Comparetores implements Comparator<AreaAnalyzesVo>{
		public int compare(AreaAnalyzesVo analyzes1, AreaAnalyzesVo analyzes2) {
	        int maxs=analyzes1.getScore()-analyzes2.getScore();
	         if(maxs==0){
	        	 int a1=(analyzes1.getTrack_normal()+analyzes1.getException_track_count())<=0?1:(analyzes1.getTrack_normal()+analyzes1.getException_track_count());
	        	 int a2=(analyzes2.getTrack_normal()+analyzes2.getException_track_count())<=0?1:(analyzes2.getTrack_normal()+analyzes2.getException_track_count());
	        	 int maxn = (int)(((double)analyzes1.getException_track_count()/a1)-((double)analyzes2.getException_track_count()/a2));
	        	 if (maxn==0) {
					return analyzes1.getScore()<=analyzes2.getScore()?-1:1;
				} else {
					return maxn;
				}
	         }else{
	 	        return maxs;
	         }
		}		
	}
	public List<Map<String,Object>> sendMail(List<OrganzationVO> list, List<AreaAnalyzesVo> areaList, String msgTime, String year, String timeType
			,String queryType,String queryTime,boolean flag) {
		List<Map<String,Object>> result = new ArrayList<>();
		try {
		DecimalFormat dft = new DecimalFormat("0.00");
		for (AreaAnalyzesVo areaAnalyzes : areaList) {
			for (OrganzationVO organzation : list) {
				if(organzation.getArea_id().equals(areaAnalyzes.getArea_id())){
					Integer enable_email = organzation.getEnable_email();
					if(enable_email != null && enable_email == 1){
						if(organzation.getEmail()!=null && !"".equals(organzation.getEmail())){
							List<AreaAnalyzesVo> areaAnalyzesList=getAreaAnalyzesList(organzation.getArea_id(),areaList);
							//获取联系人和手机号
							String contacts = organzation.getContacts();
							String email = organzation.getEmail();
							String contact_number = organzation.getContacts_number();
							//String sendMessage = getSendFormat(contacts,msgTime,areaAnalyzes,year,timeType);
							
							List<AreaAnalyzesVo> subList = new ArrayList<>();
							if(areaAnalyzesList.size()>10){
								for(int i=0;i<10;i++ ){
									subList.add(areaAnalyzesList.get(i));
								}
								for (AreaAnalyzesVo vo : areaAnalyzesList) {
									if(vo.getArea_id()==organzation.getArea_id()){
										if(!subList.contains(vo)){
											subList.add(vo);
										}
									}
								}
							}else{
								subList=areaAnalyzesList;
							}
							MailInfo info = new MailInfo();
						    info.setToAddress(email);
						    info.setSubject(config.plat_name+"区域考核统计");
						        
						    //发送html格式
						    info.setFileName("areaTemplate.html");
					        Map<String,Object> model = new HashMap<String,Object>();
							
					        model.put("contacts",organzation.getContacts());
					        model.put("year",year);
					        model.put("timeType", timeType);
					        model.put("detail",msgTime);
					        model.put("order",areaAnalyzes.getRanking());
					        model.put("vehicleCount",areaAnalyzes.getVehicle_count());
					        model.put("vehicleNetCount",areaAnalyzes.getVehicle_access_count());
					        model.put("enterpriseCount",areaAnalyzes.getEnterprise_count());
					        double dealRate = areaAnalyzes.getAlarm_count() > 0 && areaAnalyzes.getAlarm_processed() > 0 ?
					        		areaAnalyzes.getAlarm_processed()/areaAnalyzes.getAlarm_count() : 0 ;
					        model.put("dealRate",dft.format(dealRate*100)+"%");
					        model.put("pic", config.image_path);
					        model.put("tableTitle", "区域考核");
					        StringBuffer platStr = new StringBuffer();
					        for(int i=0;i<subList.size();i++){
					        	platStr.append("<tr>");
					        	//"排名:"
					        	platStr.append("<td>"+subList.get(i).getRanking()+"</td>");
					        	//"得分:"
					        	platStr.append("<td>"+subList.get(i).getScore()+"</td>");
					        	//名称
					        	platStr.append("<td>"+subList.get(i).getArea_name()+"</td>");
								//"车辆入网率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_access_rate())+"</td>");
								//"车辆上线率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_online_rate())+"</td>");
								//"在岗率:"
								platStr.append("<td>"+subList.get(i).getReply_rate()+"</td>");
								//"轨迹完整率:"
								platStr.append("<td>"+dft.format(subList.get(i).getTrack_complete_rate())+"</td>");
								//"数据合格率:"
								int trackNum = subList.get(i).getTrack_normal()+subList.get(i).getException_track_count();
								platStr.append("<td>"+(trackNum <= 0 ? 0.00 :dft.format(subList.get(i).getTrack_normal()/trackNum))+"</td>");
								platStr.append("</tr>");
					        }
					        //详细列表
					        String tableHead = " <tr><th>排名</th><th>得分</th><th>区域名称</th>" + 
					        		"<th>车辆入网率(%)</th><th>车辆上线率(%)</th><th>轨迹完整率(%)</th><th>在岗率(%)</th><th>数据合格率(%)</th></tr>";
					        model.put("tableHead",tableHead);
					        model.put("resultList",platStr);
					        result.add(model);
					        boolean status =false;
					        //  true 发送成功 false 失败
							if(flag){
								status = MailSendUtil.sendHtmlMail(info, model);
							}
					        if(status){
					        	SendMessageRecord smr = new SendMessageRecord();
					        	smr.set_id(new ObjectId());
					        	smr.setEmail(email);
					        	smr.setPhone(contact_number);
					        	smr.setTips_time(new Date());
					        	smr.setTips_type(1);
					        	smr.setTarget_type(3);
					        	smr.setTarget_name(contacts);
					        	smr.setContent("/mail/area/sendMailByArea.html?areaId="+ organzation.getArea_id() +
										"&year=" + year + "&timeType="+ timeType + "&detail=" + msgTime +
										"&queryType=" + queryType + "&queryTime=" + queryTime);
					        	saveMessage(smr);
					        	}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return result;
	}
	/*	public Map<String,Object> sendMailByHref(List<OrganzationVO> list, List<AreaAnalyzesVo> areaList, String msgTime, String year, String timeType) {
		try {
		DecimalFormat dft = new DecimalFormat("0.00");
		Map<String,Object> model = new HashMap<String,Object>();
		for (AreaAnalyzesVo areaAnalyzes : areaList) {
			for (OrganzationVO organzation : list) {
				if(organzation.getArea_id().equals(areaAnalyzes.getArea_id())){
					Integer enable_email = organzation.getEnable_email();
					if(enable_email != null && enable_email == 1){
						if(organzation.getEmail()!=null && !"".equals(organzation.getEmail())){
							List<AreaAnalyzesVo> areaAnalyzesList=getAreaAnalyzesList(organzation.getArea_id(),areaList);
							//获取联系人和手机号
							//String contacts = organzation.getContacts();
							String email = organzation.getEmail();
							//String contact_number = organzation.getContacts_number();
							
							List<AreaAnalyzesVo> subList = new ArrayList<>();
							if(areaAnalyzesList.size()>10){
								for(int i=0;i<10;i++ ){
									subList.add(areaAnalyzesList.get(i));
								}
								for (AreaAnalyzesVo vo : areaAnalyzesList) {
									if(vo.getArea_id()==organzation.getArea_id()){
										if(!subList.contains(vo)){
											subList.add(vo);
										}
									}
								}
							}else{
								subList=areaAnalyzesList;
							}
							MailInfo info = new MailInfo();
						    info.setToAddress(email);
						    info.setSubject("贵州政府平台区域考核统计");
						        
						    //发送html格式
						    info.setFileName("emailMsgTemplate.html");
							
					        model.put("contacts",organzation.getContacts());
					        model.put("year",year);
					        model.put("timeType", timeType);
					        model.put("detail",msgTime);
					        model.put("order",areaAnalyzes.getRanking());
					        model.put("vehicleCount",areaAnalyzes.getVehicle_count());
					        model.put("vehicleNetCount",areaAnalyzes.getVehicle_access_count());
					        model.put("enterpriseCount",areaAnalyzes.getEnterprise_count());
					        double dealRate = areaAnalyzes.getAlarm_count() > 0 && areaAnalyzes.getAlarm_processed() > 0 ?
					        		areaAnalyzes.getAlarm_processed()/areaAnalyzes.getAlarm_count() : 0 ;
					        model.put("dealRate",dft.format(dealRate*100)+"%");
					        model.put("pic", config.image_path);
					        model.put("tableTitle", "区域考核");
					        StringBuffer platStr = new StringBuffer();
					        for(int i=0;i<subList.size();i++){
					        	platStr.append("<tr>");
					        	//"排名:"
					        	platStr.append("<td>"+subList.get(i).getRanking()+"</td>");
					        	//"得分:"
					        	platStr.append("<td>"+subList.get(i).getScore()+"</td>");
					        	//名称
					        	platStr.append("<td>"+subList.get(i).getArea_name()+"</td>");
								//"车辆入网率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_access_rate())+"</td>");
								//"车辆上线率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_online_rate())+"</td>");
								//"在岗率:"
								platStr.append("<td>"+subList.get(i).getReply_rate()+"</td>");
								//"轨迹完整率:"
								platStr.append("<td>"+dft.format(subList.get(i).getTrack_complete_rate())+"</td>");
								//"数据合格率:"
								int trackNum = subList.get(i).getTrack_normal()+subList.get(i).getException_track_count();
								platStr.append("<td>"+(trackNum <= 0 ? 0.00 :dft.format(subList.get(i).getTrack_normal()/trackNum))+"</td>");
								platStr.append("</tr>");
					        }
					        model.put("resultList",platStr);
						  }
						}
					}
				}
			}
		return model;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}*/
	
	public List<AreaAnalyzesVo> getAreaAnalyzesList(Integer areaId, List<AreaAnalyzesVo> List) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		String FullID =queryAreaFullID(areaId);
		String[] split = FullID.split("\\.");
		if(split.length==1){
			param.put("areaId", areaId);
		}else if(split.length==2){
			FullID=split[0];
			param.put("Level", 2);
		}else if(split.length==3){
			FullID=split[0]+"."+split[1];
			param.put("Level", 3);
		}
		param.put("FullID", FullID);
		List<HashMap<String,Object>> areaIdList = queryAreaTree(param);
		List<AreaAnalyzesVo> areaList=getAreaAnalyzes(areaIdList,List);
		return areaList;
	}

	public List<AreaAnalyzesVo> getAreaAnalyzes(List<HashMap<String, Object>> areaIdList,
			List<AreaAnalyzesVo> areaList) {
		List<AreaAnalyzesVo> subList = new ArrayList<>();
		for (HashMap<String, Object> hashMap : areaIdList) {
			String id=(Long) hashMap.get("ID")+"";
			for (AreaAnalyzesVo vo : areaList) {
				if(id.equals(vo.getArea_id()+"")){
					subList.add(vo);
				}
			}
		}
		Collections.sort(subList,Collections.reverseOrder(new Comparetores()));
		sortList(subList);
		return subList;
	}
	private void sortList(List<AreaAnalyzesVo> subList) {
		int conut=1;
		for (int i = 0; i < subList.size(); i++) {
			int platScore1 = subList.get(i).getScore();
			if (i < subList.size()-1) {
				int platScore2 = subList.get(i+1).getScore();
				if (platScore1 != platScore2) {
					subList.get(i).setRanking(conut);
					conut++;
				}else {
					subList.get(i).setRanking(conut);
				}
			}else {
				subList.get(i).setRanking(conut);
			}
		}
	}

}
